package com.stockz.equity.charting.event.listener;

import java.awt.Dimension;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.event.SetStockChartPanelSizeEvent;
import com.stockz.equity.charting.view.StockChart;
import com.stockz.equity.charting.view.StockChartPanelState;
import com.stockz.equity.charting.view.StockChartPanelStructure;
import com.stockz.equity.charting.view.StockChartView;

@Component
public class SetStockChartPanelSizeEventListener implements
		ApplicationListener<SetStockChartPanelSizeEvent> {

	@Autowired StockChartView stockChartView;
	
	@Override
	public void onApplicationEvent(SetStockChartPanelSizeEvent event) {
		if(event.getSource() instanceof StockChart){
			StockChart stockChart = (StockChart)event.getSource();
			
			StockChartPanelState state = stockChart.getStockChartPanel().getStockChartPanelState();
			StockChartPanelStructure structure = stockChart.getStockChartPanel().getStockChartPanelStructure();
			
			int width = 0;
			int height = stockChart.getHeight()-stockChartView.getStockChartControlPanel().getHeight();
			if(state.getBarList() != null && !state.getBarList().isEmpty()){
				width = state.getBarList().size()*state.getTimeUnitSpace() 
						+ structure.getVoidSpaceLeftWidth() + structure.getVoidSpaceRightWidth()
						+ structure.getAxisPriceWidth() + structure.getAxisVolumeWidth();
			}else{
				width = stockChart.getStockChartPanel().getPreferredSize().width - stockChart.getVerticalScrollBar().getWidth();
			}
			Dimension dimension = new Dimension(width,height);
			stockChart.getStockChartPanel().setPreferredSize(dimension);
			stockChart.getStockChartPanel().setSize(dimension);
		}
	}
}
